const API = require('./api.js')

const app = getApp()

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 显示错误信息并返回上一页
 */
const showErrorMessageAndBack = message => {
  wx.showModal({
    content: message || "操作失败",
    showCancel: false,
    success(res) {
      if(res.confirm){
        wx.navigateBack()
      }
    }
  })
}

/**
 * 显示网络错误并返回上一页
 */
const showNetworkErrorAndBack = () => {
  wx.showModal({
    content: "网络异常，请重试",
    showCancel: false,
    success(res) {
      if(res.confirm){
        wx.navigateBack()
      }
    }
  })
}

/**
 * 添加查询记录
 */
const addQueryHistory = (productId, productName, productImageUrl) => {
  const app = getApp()
  if(!app.globalData.isLogin || app.globalData.usertype != "customer"){
    return
  }

  wx.request({
    url: API.Customer.queryRecord,
    method: 'POST',
    data: {
      "customer_id": app.globalData.userinfo.id,
      "product_id": productId,
      "product_name": productName,
      "product_image": productImageUrl
    },
    success (res) {
      if(res.data.code == "SUCCESS"){
        console.log("查询记录添加成功")
      }else{
        console.log("查询记录添加失败")
      }
    },
    fail () {
      console.log("查询记录添加失败")
    }
  })
}

function showNetworkError() {
  wx.showModal({
    content: "网络连接失败，请检查后重试",
    showCancel: false,
  })
}

function showErrorMessage(message) {
  wx.showModal({
    content: message,
    showCancel: false,
  })
}

function showSuccessToast(message, duration) {
  wx.showToast({
    title: message,
    duration: duration
  })
}

function showTips(message, duration) {
  wx.showToast({
    title: message,
    icon: 'none',
    duration: duration
  })
}

function getData(url, params) {
  return new Promise((resolve,rejuct) => {
    wx.request({
      url: url,
      method: "GET",
      data: params,
      success(res){
        if(res.data.code == "SUCCESS") {
          resolve(res.data.data)
        } else {
          rejuct(res.data)
        }
      },
      fail(err) {
        rejuct(err)
      }
    })
  })
}

function checkCameraPermission(errMessage, gotoUrl) {
  wx.getSetting({
    success (res) {
      if(res.authSetting['scope.camera'] == null){
        wx.authorize({
          scope: 'scope.camera',
          success(){
            wx.navigateTo({
              url: gotoUrl,
            })
          },
          fail() {
            wx.showToast({
              title: errMessage,
              icon: 'none',
              duration: 2000
            })
          }
        })
      }else if(res.authSetting['scope.camera'] == false){
        wx.showModal({
          content: errMessage,
          confirmText: "去授权",
          success(res) {
            if(res.confirm){
              wx.openSetting()
            }
          }
        })
      }else if(res.authSetting['scope.camera'] == true){
        wx.navigateTo({
          url: gotoUrl,
        })
      }
    }
  })
}

module.exports = {
  formatTime: formatTime,
  formatNumber: formatNumber,
  showErrorMessageAndBack: showErrorMessageAndBack,
  showNetworkErrorAndBack: showNetworkErrorAndBack,
  addQueryHistory: addQueryHistory,
  showNetworkError: showNetworkError,
  showErrorMessage: showErrorMessage,
  showSuccessToast: showSuccessToast,
  showTips: showTips,
  getData: getData,
  checkCameraPermission: checkCameraPermission
}
